package com.hyacinth.cloudnote.common.config.auditing;

import com.hyacinth.cloudnote.common.security.CurrentUserContextHolder;
import com.hyacinth.cloudnote.common.security.UserPrincipal;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

import java.util.Optional;
import java.util.UUID;

/**
 * @author zhangfb
 */
@Configuration
@EnableJpaAuditing
public class JpaAuditingConfig {

    @Lazy
    @Bean
    public AuditorAware<UUID> auditorProvider() {
        return () -> {
            UserPrincipal currentUser = CurrentUserContextHolder.getCurrentUser();
            if (currentUser == null) {
                return Optional.empty();
            }
            return Optional.of(currentUser.getId());
        };
    }
}
